<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\library\Excel;
use app\admin\model\GoodsPics;
use PhpOffice\PhpSpreadsheet\Writer\Xls\Xf;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\facade\Db;
use think\facade\Filesystem;
use think\Image;
use think\Request;
use think\facade\View;
use app\admin\model\Goods  as GoodsModel;

use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\exception\ValidateException;



class Goods
{
    //通过依赖注入的形式加载模型类、不用每个方法实例化对象、依赖注入
    public $goodsModel;//公共属性
    // 构造方法
    public function __construct(GoodsModel $goodsModel)
    {
        //属性复制
        $this->goodsModel = $goodsModel;
    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        # 搜索关键字
        # 商品列表
        // 查询所有数据 select()方法
        //$data = $this->goodsModel::select();
        //分页查询 paginate()方法
        //保留搜索条件分页
        $goods_name = \request()->get('goods_name');//搜索条件
        $create_time = \request()->get('create_time');//搜索条件
        $where = [];
        // 判断商品名称是否传送
        if ($goods_name) {
            $where[] = ['goods_name','like', "%{$goods_name}%"];
        }
        // 判断查询时间是否传送
        if ($create_time ) {
                $where[] = ['create_time' ,'=' ,strtotime($create_time)];
        }
//        # 查询包括软删除掉的数据 withTrashed
//        $all  = $this->goodsModel::withTrashed()->select();
//        # 只查询软删除的数据 onlyTrashed
//        $softDelete  = $this->goodsModel::onlyTrashed()->select();

        $data = $this->goodsModel::where($where)->paginate([
            'list_rows' => 10,
            'query' => [
                'goods_name' => $goods_name,
                'create_time' => $create_time,
            ]
        ]);
        # 赋值、渲染模版
        // 高亮展示
        foreach ($data as $key => $value) {
            $data[$key]['goods_name'] = str_replace($goods_name,"<font color='red'>{$goods_name}</font>",$value['goods_name']);
        }
        //方式一
        View::assign('data',$data);
        View::assign('goods_name',$goods_name); //把搜索内容返回给表单
        View::assign('create_time',$create_time); //把搜索内容返回给表单
        return  View::fetch('admin/goods_list');
        //方式二、渲染模版、并赋值
//        return  View::fetch('admin/goods_list',['data' => $data]);
        //
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }

//    /**
//     * 商品添加页面
//     * tp6 默认访问控制器目录、方法名.html
//     */
//    public function goodsAdd(){
//        //get 方式提交展示图
//        return View::fetch('admin/goods_add');
//    }
//
//    /**
//     * 添加用什么方法
//     */
//    public function insert(){
//        // post 添加数据
//        return '添加成功';
//    }
    /**
     * @return string
     */
    public function goodsAdd(GoodsPics $goodsPics){
//        date("Y-m-d H:i:s",)
        # 如果是post提交
        if (\request()->isPost()) {
            try {
                //接值
                $data = \request()->all();
//                trim() ltrim() rtrim()
                $data['goods_name'] = trim($data['goods_name']);
                // 通过验证器验证表单信息
                validate(\app\admin\validate\Goods::class)->batch(true)->check($data);
                // 上传文件
                // 缩略图
                $data['goods_logo'] = Filesystem::disk('public')->putFile( 'image', $data['goods_logo']);
                $image = \think\Image::open('admin/'.$data['goods_logo']);
                // 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.png
                # 按比例缩放
//                $image->thumb(150,150)->save('admin/'.$data['goods_logo']);
                # 剪切
//                $image->thumb(150,150,\think\Image::THUMB_CENTER)->save('admin/'.$data['goods_logo']);
                // 反转
                // 对图像进行以x轴进行翻转操作
                //$image->flip()->save('admin/'.$data['goods_logo']);
                // 对图像进行以y轴进行翻转操作
//                $image->flip(\think\image::FLIP_Y)->save('./filp_image.png');
                // 给原图左上角添加水印并保存water_image.png

                $image->water('admin/image/20211214/80fe7f53f875f746ff4b09c66e4b13b9.png',\think\Image::WATER_NORTHWEST)->text('十四个月','static/font/ariblk.ttf',20,'#ffffff')->save('admin/'.$data['goods_logo']);
                dd($data['goods_logo']);
                $this->goodsModel->save($data);
                // 批量添加商品图片
                //多图片上传
                $goods_pics = [];
                foreach ($data['goods_pics'] as $value) {
                    $goods_pics[] = [
                        'goods_id' => $this->goodsModel->id,//获取新添加的id
                        'pics_big' => Filesystem::disk('public')->putFile( 'image', $value)
                    ];
                }
                // 保存入库
                $goodsPics->saveAll($goods_pics);
                //dd($this->goodsModel::getLastSql()); //获取最后一条SQL
                //添加数据
                return  redirect('goodsList');
            }catch (\think\exception\ValidateException $e){
                $data =  $e->getError();
                dd($data);
            }
        } else {

            //查询分类

            //get提交、展示视图
             return View::fetch('admin/goods_add');
        }
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        # 查询数据
        //创建模型
        $goods_info = $this->goodsModel::find($id);
        View::assign('goodsInfo',$goods_info);//赋值
        return View::fetch('admin/goods_edit');//渲染模版
    }

    /**
     * 更新数据
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\think\response\Redirect
     */
    public function goodsUpdate(Request $request){
        // 接值
       $data = $request->all();
        // 查询并更新
       $goodsInfo = $this->goodsModel::find($data['id']);
       $goodsInfo->goods_name = $data['goods_name'];
       $goodsInfo->goods_price = $data['goods_price'];
       $goodsInfo->goods_logo = $data['goods_logo'];
       $goodsInfo->goods_number = $data['goods_number'];
       $goodsInfo->goods_introduce = $data['goods_introduce'];
       $goodsInfo->save();
       // 跳转列表页码
        return redirect('goodsList');
    }

    /**
     * 删除数据
     * @param $id
     * @return \think\response\Json
     */
    public function goodsDel($id) {
        $goodsInfo = $this->goodsModel::find($id);
        $result = $goodsInfo->delete();
        if ($result) {
            return json(['code' => 0,'data' => [],'msg' => 'ok']);
        } else {
            return json(['code' => 2001,'data' => [],'msg' => '修改失败']);
        }
    }

    /**
     * 修改商品状态
     * @param $id
     * @return \think\response\Json
     */
    public function goodsState($id) {
        $goodsInfo = $this->goodsModel::find($id);
        // 如果数据库里面是上架、改成下架、如果数据库里面是下、改成已架
        if ($goodsInfo->goods_state == 1) {
            $goodsInfo->goods_state = 0;
        } else {
            $goodsInfo->goods_state = 1;
        }
        $result = $goodsInfo->save();

        if ($result) {
            return json(['code' => 0,'data' => [],'msg' => 'ok']);
        } else {
            return json(['code' => 2001,'data' => [],'msg' => '修改失败']);
        }
    }

    /**
     * 导出商品
     * @param Excel $excel
     */
    public function goodsExport(Excel $excel,Request $request){
        $data = [
            ['title1' => '111', 'title2' => '222'],
            ['title1' => '111', 'title2' => '222'],
            ['title1' => '111', 'title2' => '222']
        ];
        $title = ['第一行标题', '第二行标题'];

        // Create new Spreadsheet object
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // 方法一，使用 setCellValueByColumnAndRow
        //表头
        //设置单元格内容
        foreach ($title as $key => $value) {
            // 单元格内容写入
            $sheet->setCellValueByColumnAndRow($key + 1, 1, $value);
        }
        $row = 2; // 从第二行开始
        foreach ($data as $item) {
            $column = 1;
            foreach ($item as $value) {
                // 单元格内容写入
                $sheet->setCellValueByColumnAndRow($column, $row, $value);
                $column++;
            }
            $row++;
        }

        // 方法二，使用 setCellValue
        //表头
        //设置单元格内容
        $titCol = 'A';
        foreach ($title as $key => $value) {
            // 单元格内容写入
            $sheet->setCellValue($titCol . '1', $value);
            $titCol++;
        }
        $row = 2; // 从第二行开始
        foreach ($data as $item) {
            $dataCol = 'A';
            foreach ($item as $value) {
                // 单元格内容写入
                $sheet->setCellValue($dataCol . $row, $value);
                $dataCol++;
            }
            $row++;
        }
        ob_end_clean();
        // Redirect output to a client’s web browser (Xlsx)
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="01simple.xlsx"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        exit;
        ini_set('error_reporting',"E_ALL");
        // 设置表格的表头数据
        $header = ["A1" => "编号", "B1" => "姓名", "C1" => "年龄"];
        // 假设下面这个数组从数据库查询出的二维数组
        $data = [
            [1,'one'],
            [2,'two'],
            [3,'three'],
            [4,'four'],
            [5,'five']
        ];

        // 实例化类
        $preadsheet = new Spreadsheet();
        // 创建sheet
        $sheet = $preadsheet->getActiveSheet();
        // 循环设置表头数据
        foreach ($header as $k => $v) {
            $sheet->setCellValue($k, $v);
        }
        // 生成数据
        $sheet->fromArray($data, null, "A2");
        header("Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

        // 激活浏览器窗口
        header("Content-Disposition:attachment;filename=test.xlsx");
        //缓存控制
        header("Cache-Control:max-age=0");
        // 调用方法执行下载
        $writer = IOFactory::createWriter($preadsheet, 'xlsx');
        // 数据流
        $writer->save("php://output");
        ob_clean();

    }

    /**
     * 导入商品
     * @param Excel $excel
     */
    public function goodsImport(Excel $excel){
       return View::fetch('admin/test');
    }
}
